package com.jia.lightrailsystem

import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory
import com.blankj.utilcode.util.ToastUtils
import com.jia.lightrailsystem.databinding.ActivityMainBinding
import priv.songxusheng.easystorer.EasyStorer
import androidx.core.graphics.toColorInt
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import androidx.core.content.FileProvider
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.LogUtils

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private lateinit var mainVM: MainVM
    private var downloadProgressDialog: DownloadProgressDialog? = null
    private val okHttpClient = OkHttpClient()


    companion object {
        const val TAG = "ActivityMainBinding"
    }

    private var myDialog : AlertDialog? = null
    private var myAddressDialog :AddressAlertDialog? = null

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        mainVM = ViewModelProvider(
            this,
            AndroidViewModelFactory.getInstance(application)
        ).get(MainVM::class.java)
//        downloadAndInstallApk("http://a.afsdown.com/apk3/XAPKInstaller_v4.6.4.1_anfensi.com.apk?auth_key=1749217806-DqTNLYp2U00BFBVy-0-df551c46e4b9156e0b2a1e59297bfa2b")

        myDialog = AlertDialog(this).builder()
        myAddressDialog = AddressAlertDialog(this).builder()

        // 直接赋值 ViewModel 到 SocketClient
//        SocketClient.mainViewModel = mainVM
        mainVM.initUart()
        mainVM.initSocket(mainVM)
        UartUtil.onDataSend("{\"cmd\":\"control\",\"dianji\":{\"yd\":\"H\"}}")
// 监听连接状态
        lifecycleScope.launch {
            SocketClient.connectionStatus.collect { isConnected ->
                if (isConnected) {
                    LogUtils.d("已连接")
                } else {
                    LogUtils.d("连接断开，正在重连...")
                }
            }
        }
        lifecycleScope.launch {
            Http.deviceData(VersionUtils.getAppVersionName(this@MainActivity)){ it->
            EasyStorer.put("pwd", it.passwd)//设置密码
                mainLooper.runCatching {
                    //判断一下是否升级
                    if (it.updata == 1) {
                        //升级url
                        downloadAndInstallApk(it.url)
                    }
                    binding.total.text = it.statistics?.check_total.toString()
                    binding.success.text = it.statistics?.pass.toString()
                    it.statistics?.pass_rate?.toInt()
                        ?.let { it1 ->
                            val angle = if (it?.statistics?.check_total?.toIntOrNull() == 0 ||
                                it?.statistics?.pass_rate?.toIntOrNull() == 0) {
                                0
                            } else {
                                (it?.statistics?.pass_rate!!.toInt() * 360) / it?.statistics?.check_total?.toInt()!!
                            }
                            binding.wheelprogress.setPercentage(angle)
                            binding.wheelprogress.setStepCountText("${angle}%")
                        }
                }
        }}

        val blue = getResources().getColor(R.color.blue)
        val white = getResources().getColor(R.color.white)
        mainVM.deviceStatus.observe(this) {
            binding.tvCar.text = "轨枕车    ${it.car}"
            binding.tvMoving.text = it.moving
            binding.tvOverallStatus.text = it.overallStatus
            binding.tvLight.text = "灯           ${it.light}"
            binding.tvCamera2D.text = "2D相机   ${it.camera2D}"
            binding.tvCamera3D.text = "3D相机   ${it.camera3D}"
            binding.tvPrinter.text = "喷码机    ${it.printer}"
            binding.total.text = it.statistics?.check_total.toString()
            binding.success.text = it.statistics?.pass.toString()
            it.statistics?.pass_rate?.toInt()
                ?.let { it1 ->
                    val angle = (it?.statistics?.pass_rate!!.toInt() * 360) / it?.statistics?.check_total?.toInt()!!
                    binding.wheelprogress.setPercentage(angle)
                    binding.wheelprogress.setStepCountText("${angle}%")
                }

            Log.d(TAG, "deviceStatus: $it")
        }

        binding.llDialog.setOnClickListener {
            myDialog?.setGone()?.setTitle("系统设置")?.setMsg("请输入密码")
                ?.setNegativeButton("取消", null)?.setPositiveButton("确定",
                    View.OnClickListener {
                        val pwd = EasyStorer.get("pwd", "123456")
                        if (pwd == myDialog?.txt_msg?.text.toString())  {
                            //密码正确
                            myDialog?.dismiss()
                            ButtonDialog(this).builder().setTitle("系统设置")
                                .setNegativeButton("关闭", null)
                                .setMsgButton(/* text = */ "配置",
                                    /* listener = */ View.OnClickListener {
                                        val photoIp = EasyStorer.get("photoIp", "")
                                        val photoPort = EasyStorer.get("photoPort", "")
                                        val serverIp = EasyStorer.get("serverIp", "")
                                        myAddressDialog?.setTitle("系统设置")?.setText(serverIp,photoIp,photoPort)
                                            ?.setNegativeButton("取消", null)?.setPositiveButton("确定",
                                                View.OnClickListener {
                                                    if (myAddressDialog?.serverIp()?.isEmpty() == true) {
                                                        ToastUtils.showShort("请输入服务器地址")
                                                        return@OnClickListener
                                                    }
                                                    if (myAddressDialog?.photoIp()?.isEmpty() == true) {
                                                        ToastUtils.showShort("请输入相机地址")
                                                        return@OnClickListener
                                                    }
                                                    if (myAddressDialog?.photoPort()?.isEmpty() == true) {
                                                        ToastUtils.showShort("请输入相机端口")
                                                        return@OnClickListener
                                                    }
                                                    //保存
                                                    EasyStorer.put("photoIp", myAddressDialog?.photoIp())//设置密码
                                                    EasyStorer.put("photoPort", myAddressDialog?.photoPort())//设置密码
                                                    EasyStorer.put("serverIp", myAddressDialog?.serverIp())//设置密码
                                                    myAddressDialog?.dismiss()
                                                })?.show()
                                    }
                                )
                                .setPositiveButton("系统配置",
                                    View.OnClickListener {

                                    }).show()
                        }else{
                            ToastUtils.showShort("密码错误")
                        }
                    })?.show()
        }
    }

    private fun downloadAndInstallApk(url: String) {
        downloadProgressDialog = DownloadProgressDialog(this).apply {
            show()
            setFileName("update.apk")

        }

        CoroutineScope(Dispatchers.IO).launch {
            try {
                val request = Request.Builder()
                    .url(url)
                    .build()

                val response = okHttpClient.newCall(request).execute()
                if (!response.isSuccessful) {
                    throw IOException("下载失败: ${response.code()}")
                }

                val responseBody = response.body()
                val contentLength = responseBody?.contentLength() ?: 0L
                val file = File(getExternalFilesDir(null), "update.apk")
                val inputStream = responseBody?.byteStream()
                val outputStream = FileOutputStream(file)

                withContext(Dispatchers.Main) {
                    downloadProgressDialog?.setTotalSize(contentLength)
                }

                var downloadedSize = 0L
                val buffer = ByteArray(8192)
                var bytesRead: Int

                while (inputStream?.read(buffer).also { bytesRead = it ?: -1 } != -1) {
                    outputStream.write(buffer, 0, bytesRead)
                    downloadedSize += bytesRead

                    withContext(Dispatchers.Main) {
                        downloadProgressDialog?.updateProgress(downloadedSize)
                    }
                }

                outputStream.close()
                inputStream?.close()
                responseBody?.close()

                withContext(Dispatchers.Main) {
                    downloadProgressDialog?.dismiss()
                    installApk(file)
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    downloadProgressDialog?.dismiss()
                    ToastUtils.showShort("下载失败：${e.message}")
                }
            }
        }
    }

    private fun installApk(file: File) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (!packageManager.canRequestPackageInstalls()) {
                val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
                intent.data = Uri.parse("package:$packageName")
                startActivity(intent)
                return
            }
        }
        val uri = FileProvider.getUriForFile(
            this,
            "${packageName}.fileprovider",
            file
        )
        val intent = Intent(Intent.ACTION_VIEW).apply {
            setDataAndType(uri, "application/vnd.android.package-archive")
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        startActivity(intent)
    }
}